﻿//
// deployment.js
//

// Deployments View-model with initial state
var deploymentsViewModel = {
    deployments: ko.observableArray(initialDeploymentData),
    deploymentBuildTargetHosts: ko.observableArray(initialDeploymentBuildTargetHostsData),
    currentDateTimeBinding: ko.observable(currentDateTime),
    currentPageTitle: ko.observable(pageTitle),
    setDocumentTitle: function () {
        document.title = this.currentPageTitle();
    },
    getActiveDeploymentsCount: function () {
        var activeDeploymentsCount = 0;
        for (var i = 0; i < this.deployments().length; i++) {
            if (this.deployments()[i].IsActive == true) activeDeploymentsCount++;
        }
        return activeDeploymentsCount;
    }
};

ko.applyBindings(deploymentsViewModel, document.body);

$(".last-refreshed-caption").attr("text", Date());

(function refreshDeploymentsFromServer() {

    // Each call uses a timer that expires after the call so that we are not
    // queuing timer events.
    setTimeout(function () {
        // Generate a random number to bypass the browser cache.
        var randomnumber = Math.floor(Math.random() * 99999999);

        // Make AJAX call to the server to get fresh deployments JSON data.  
        $.getJSON(applicationPath + 'package/refresh/?' + randomnumber, function (results) {
            deploymentsViewModel.deployments(results);
        });

        // Make AJAX call to the server to get fresh hosts JSON data.  
        $.getJSON(applicationPath + 'package/refresh/' + packageName + '/?' + randomnumber, function (results) {
            deploymentsViewModel.deploymentBuildTargetHosts(results);
        });

        //window.status = "Last refreshed from server on " + Date();
        deploymentsViewModel.currentDateTimeBinding(Date());

        var activeDeploymentsCount = deploymentsViewModel.getActiveDeploymentsCount();
        deploymentsViewModel.currentPageTitle((activeDeploymentsCount > 0? "(" + activeDeploymentsCount + ") " : "") + basePageTitle);
        deploymentsViewModel.setDocumentTitle();

        // Keep calling yourself indefinitely and reset timer.
        refreshDeploymentsFromServer();

    }, timerIntervalInMilliseconds);
})();

// Bind an event handler for the "check-all-hosts" checkbox.
$("#AllCheckBoxes").bind('click', function () {
    if (this.checked) { checkAllBoxes() } else { uncheckAllBoxes() }
});

// Bind an event handler for the individual checkbox clicks.
$(".hostCheckBoxes").live('click', function () {
    var id = $(this).attr("id");
    var checkedState = $(this).attr("checked");
    var savedStateIndex = checkBoxDataExist(id);

    if (checkedState != "checked") {
        //$(this).css('background-color', '');
        if (savedStateIndex >= 0) { delete checkboxData[savedStateIndex]; }
    }
    else {
        //$(this).css('background-color', 'lightblue');
        if (savedStateIndex < 0) { checkboxData.push(id); }
    }
});

$(function () {
    $('#deploymentDetailsDialog').dialog({
        autoOpen: false,
        width: 950,
        height: 700,
        minWidth: 400,
        minHeight: 300,
        modal: true,
        open: function (event, ui) {
            var hostName = $(this).attr('hostname');
            var hostNameWithoutPrefix = hostName.replace('dialog_', '');
            var randomnumber = Math.floor(Math.random() * 99999999);
            $.get(applicationPath + 'package/' + packageName + '/details/' + hostNameWithoutPrefix + '?' + randomnumber, function (results) {
                $('#deploymentDetailsDialog').html(results);
            });
        },
        buttons: {
            "Close": function () {
                $('#deploymentDetailsDialog').dialog("close");
            }
        }
    });
});

//
// Helper functions.
//

function checkAllBoxes() {
    checkboxData = [];
    var checkboxes = $(".hostCheckBoxes").each(function () {
        var id = $(this).attr("id");
        checkboxData.push(id);
    });
    $(".hostCheckBoxes").attr('checked', 'checked');
}

function uncheckAllBoxes() {
    checkboxData = [];
    $(".hostCheckBoxes").removeAttr('checked');
}

function getCheckedState(id) {
    if (id == 'host_N/A') return "";

    var savedStateIndex = checkBoxDataExist(id);
    if (savedStateIndex < 0) {
        return "";
    }
    else {
        return "checked"
    };
}

function checkBoxDataExist(dataValue) {
    if (checkboxData.length == 0) return -1;

    for (var counter = 0; counter < checkboxData.length; counter++) {
        if (checkboxData[counter] == dataValue) {
            return counter;
        }
    }

    return -1;
}

function openDeploymentDetailsDialog(element) {
    var hostname = $(element).attr('id');
    $('#deploymentDetailsDialog').attr('hostname', hostname);
    $('#deploymentDetailsDialog').dialog("open");
}

function showStatusCount (element) {
    var statusBox = '#stats_' + $(element).attr('id');
    $(statusBox).css('visibility', 'visible');
}

function hideStatusCount(element) {
    var statusBox = '#stats_' + $(element).attr('id');
    $(statusBox).css('visibility', 'hidden');
}
